﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

using ZhimeiSoft.CharmManager.DOL;
using ZhimeiSoft.CharmManager.Server.BLL.Interface;
using ZhimeiSoft.CharmManager.Server.Factory;
using ZhimeiSoft.CharmManager.Server.DAL;
using ZhimeiSoft.CharmManager.Server.DAL.Interface;

namespace ZhimeiSoft.CharmManager.Server.BLL
{
    public class ServiceItemCategoryBLL : IServiceItemCategoryBLL
    {
        IServiceItemCategoryDAL serviceItemCategoryDAL;

        IServiceItemBLL serviceItemBLL;

        public ServiceItemCategoryBLL()
        {
            serviceItemCategoryDAL = BaseDalFactory.CreateServiceItemCategoryDal();
            serviceItemBLL = BaseBLLFactory.CreateServiceItemBLL();
        }

        #region IServiceItemCategoryBLL 成员

        public void InsertServiceItemCategory(DBEntityServiceItemCategory category)
        {
            serviceItemCategoryDAL.InsertServiceItemCategory(category);
        }

        public void UpdateServiceItemCategory(DBEntityServiceItemCategory category)
        {
            serviceItemCategoryDAL.UpdateServiceItemCategory(category);
        }

        public void DeleteServiceItemCategory(int categoryid)
        {
            List<int> listDeletedCategory = new List<int>();
            listDeletedCategory.Add(categoryid);
            int iParentCategoryID = 0;
            //1. 先获取当前分类的上级分类ID
            string sFilter = string.Format("{0}={1}", DBEntityServiceItemCategory.FieldName.SCATEGORYID, categoryid.ToString());
            DataSet ds = serviceItemCategoryDAL.QueryServiceItemCategory(sFilter);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                DBEntityServiceItemCategory category = new DBEntityServiceItemCategory(dr);
                iParentCategoryID = category.SPARENTCATEGORYID;
            }
            //2. 获取当前分类下的所有下级分类ID
            sFilter = string.Format("{0}={1}", DBEntityServiceItemCategory.FieldName.SPARENTCATEGORYID, categoryid.ToString());
            DataSet newDs = serviceItemCategoryDAL.QueryServiceItemCategory(sFilter);
            foreach (DataRow dr in newDs.Tables[0].Rows)
            {
                DBEntityServiceItemCategory category = new DBEntityServiceItemCategory(dr);
                listDeletedCategory.Add(category.SCATEGORYID);
            }
            //3. 将当前分类以及所有下级分类下的服务项目都调整到上级分类下
            foreach (int s in listDeletedCategory)
            {
                serviceItemCategoryDAL.DeleteServiceItemCategory(s);
                serviceItemBLL.ResetServiceItemCategory(s, iParentCategoryID);
            }
        }

        public DataSet QueryServiceItemCategory(string sFilter)
        {
            return serviceItemCategoryDAL.QueryServiceItemCategory(sFilter);
        }

        #endregion
    }
}
